package org.jeese.modules.sys.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.jeese.common.properties.ShiroProperties;
import org.jeese.modules.sys.entity.SysMenu;
import org.jeese.modules.sys.service.SysMenuService;
import org.jeese.modules.sys.service.SysShiroService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("sysShiroService")
public class SysShiroServiceImpl implements SysShiroService {
	private static final Logger logger = LoggerFactory.getLogger(SysShiroServiceImpl.class);
	
	@Autowired
	private ShiroProperties shiroProperties;
	@Autowired
	private SysMenuService menuService;
	@Autowired  
    private ShiroFilterFactoryBean shiroFilterFactoryBean; 

	
	@Override
	@PostConstruct
	public void initPermession() {
		AbstractShiroFilter shiroFilter = null;  
        try {  
            shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();  
        } catch (Exception e) {  
        	logger.error(e.getMessage());  
        	throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
        }  

        // 获取过滤管理器  
        PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter  
                .getFilterChainResolver();  
        DefaultFilterChainManager filterChainManager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();  
        // 清空初始权限配置  
        filterChainManager.getFilterChains().clear();  
        shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();  

        // 重新构建生成  
        shiroFilterFactoryBean.setFilterChainDefinitionMap(getFilterChainDefinitionMap());
        // 重新构建生成  
        shiroFilterFactoryBean.setFilterChainDefinitionMap(getFilterChainDefinitionMap());  
        Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();  
        for (Map.Entry<String, String> entry : chains.entrySet()) {  
			filterChainManager.createChain(entry.getKey(), entry.getValue()); 
        }  
        logger.debug("init shiro permission success...");  
	}
	
	/**
	 * 读取权限资源
	 * @return
	 */
	private Map<String, String> getFilterChainDefinitionMap() {
		Map<String, String> map = shiroProperties.getMap();
		List<SysMenu> list = menuService.getAllMenuList();
		if (list != null && list.size() > 0) {
			String permKey = "";
			String permUrl = "";
			for (SysMenu menu : list) {
				permKey = menu.getPerms();
				permUrl = menu.getUrl();
				if (StringUtils.isNotEmpty(permKey) && StringUtils.isNotEmpty(permUrl)) {
					map.put(permUrl + "", "perms[" + permKey + "]");
				}
			}
		}
		// 所有资源的访问权限，必须放在最后
		map.put("/**", "authc");
		return map;
	}
    
	@Override
	public void updatePermession() {
		synchronized (shiroFilterFactoryBean) {  
            AbstractShiroFilter shiroFilter = null;  
            try {  
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();  
            } catch (Exception e) {  
            	logger.error(e.getMessage());  
            	throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }  
  
            // 获取过滤管理器  
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter  
                    .getFilterChainResolver();  
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();  
  
            // 清空初始权限配置  
            manager.getFilterChains().clear();  
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();  
  
            // 重新构建生成  
            shiroFilterFactoryBean.setFilterChainDefinitionMap(getFilterChainDefinitionMap());  
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();  
			for (Map.Entry<String, String> entry : chains.entrySet()) {
				manager.createChain(entry.getKey(), entry.getValue());
			}
            logger.debug("update shiro permission success...");  
        }  
	}
}
